
#include "./redirect_process_output.h"
#include "./logger.h"

#include "nosal/log/logger.h"
#include "nosal/log/logging.h"

#include <cstring>
#include <string>

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <strings.h>

namespace netaos {
namespace nosal {
namespace exec {
namespace internal {

namespace
{
netaos::nosal::log::Logger& GetLogger()
{
    static netaos::nosal::log::Logger& logger
        = netaos::nosal::log::CreateLogger("RDRT", "Redirect Process Output", netaos::nosal::exec::internal::kLogLevel);
    return logger;
}
}  // namespace

static constexpr auto kOutputDirectory = "/var/redirected";
static constexpr auto kEnvironmentVar = "REDIRECT_TERMINAL";

static inline bool IsRedirectionEnabled()
{
    auto val = getenv(kEnvironmentVar);
    if (val == nullptr || strcasecmp(val, "true") == 0 || std::strcmp(val, "1") == 0) {
        return true;
    }
    return false;
}

void RedirectProcessOutput(const char* const fileName)
{
    static bool redirectionEnabled = IsRedirectionEnabled();
    if (!redirectionEnabled) {
        return;
    }
    if (fileName == nullptr || std::strlen(fileName) < 1) {
        return;
    }
    mkdir(kOutputDirectory, S_IRWXU);
    std::string outputFile{kOutputDirectory};
    outputFile += '/';
    outputFile += fileName;
    int fd = open(outputFile.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR);
    bool isError = false;
    if (dup2(fd, STDOUT_FILENO) == -1) {
        isError = true;
    }
    if (dup2(fd, STDERR_FILENO) == -1) {
        isError = true;
    }
    std::string inputFile(fileName);
    if (not isError) {
        GetLogger().LogInfo() << "Output of" << '\'' + inputFile + '\'' << "file has been redirected to"
                              << '\'' + outputFile + '\'';
    } else {
        GetLogger().LogError() << "Output of" << '\'' + inputFile + '\'' << "file has NOT been redirected to"
                               << '\'' + outputFile + '\'';
    }
}

}  // namespace internal
}  // namespace exec
}  // namespace nosal
}  // namespace netaos
